package me.project.scheduling_delete.schedule;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.File;
import java.nio.file.*;

@Component
public class FolderCleanupTask {

    private static final String DIRECTORY_PATH = "D:\\do\\";

    @Scheduled(fixedRate = 600000) // 600,000 milliseconds = 10 minutes
    public void checkAndDeleteFolder() {
        File directory = new File(DIRECTORY_PATH);
        if (canDelete(directory)) {
            deleteContents(directory);
            System.out.println("Contents of the directory deleted successfully.");
        } else {
            System.out.println("Directory is currently in use or does not exist.");
        }
    }

    private boolean canDelete(File directory) {
        try {
            if (directory.exists()) {
                Path path = directory.toPath();
                try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
                    return true;
                } catch (Exception e) {
                    return false; // Directory is in use
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void deleteContents(File directory) {
        File[] allContents = directory.listFiles();
        if (allContents != null) {
            for (File file : allContents) {
                deleteRecursively(file);
            }
        }
    }

    private void deleteRecursively(File file) {
        if (file.isDirectory()) {
            File[] contents = file.listFiles();
            if (contents != null) {
                for (File f : contents) {
                    deleteRecursively(f);
                }
            }
        }
        file.delete();
    }
}
